package com.darsystems.foghourz.server;

import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class FBUserConfigStore {

	private final static Logger log = Logger.getLogger(FBUserConfigStore.class.getName());
	
	private static User getUser()
	{
		UserService userService = UserServiceFactory.getUserService();
	    return userService.getCurrentUser();
	}
	
	public static String setUserFBServer(String fbUrl)
	{
		User user = getUser();

	    if(user == null)
	    {
	    	log.warning("No user is logged in!");
	    	return null;
	    }
	    
	    FBServerInfoRecord info = new FBServerInfoRecord(user, fbUrl);

	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    try
	    {
	    	pm.makePersistent(info);
	    }
	    finally
	    {
	    	pm.close();
	    }
	    return fbUrl;
	}
	
	public static String getUserFBServer()
	{
	    User user = getUser();

	    if(user == null)
	    {
	    	log.warning("No user is logged in!");
	    	return null;
	    }
	    
	    PersistenceManager pm = PMF.get().getPersistenceManager();
	    try
	    {
	    	Query query = pm.newQuery(FBServerInfoRecord.class);
	        query.setFilter("fbUserEmail == fbUserParam");
	        query.declareParameters("String fbUserParam");

	        FBServerInfoRecord info = null;
	        try {
	            List<FBServerInfoRecord> results = (List<FBServerInfoRecord>) query.execute(user.getEmail());
	            if (results.size() > 0)
	            {
	            	info = results.get(0);
	            } 
	        }
	        finally {
	            query.closeAll();
	        }
	        
	        String fbUrl = info == null ? "" : info.getFbUrl();
	        return fbUrl;
	    }
	    finally
	    {
	    	pm.close();
	    }
	}
}
